package com.elem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.elem.bean.Cart;
import com.elem.bean.User;
import com.elem.service.CartService;
import com.elem.service.UserService;
import com.elem.service.impl.CartServiceImpl;
import com.elem.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

// 目前只有两个：一个是登录，一个是注册
@WebServlet("/CartController/*")
public class CartServlet extends BaseServlet {

    CartService cartService =  new CartServiceImpl();
    ObjectMapper objectMapper = new ObjectMapper();
    public void removeCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        Cart cart =  new Cart();
        try {
            BeanUtils.populate(cart, req.getParameterMap());
            int row = cartService.removeCart(cart);
            objectMapper.writeValue(resp.getOutputStream(), row);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void updateCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        Cart cart =  new Cart();
        try {
            BeanUtils.populate(cart, req.getParameterMap());
            int row = cartService.updateCart(cart);
            objectMapper.writeValue(resp.getOutputStream(), row);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    public void saveCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        Cart cart =  new Cart();
        try {
            BeanUtils.populate(cart, req.getParameterMap());
            int row = cartService.saveCart(cart);
            objectMapper.writeValue(resp.getOutputStream(), row);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    // 检验用户手机号是否存在
    public void listCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        Cart cart =  new Cart();
        try {
            BeanUtils.populate(cart, req.getParameterMap());
            List<Cart> cartList = cartService.listCart(cart);
            objectMapper.writeValue(resp.getOutputStream(), cartList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}